﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ATest.Bll
{
    public partial class Test : BaseItem, Interfaces.IValidate
    {
        public virtual DateTime Created
        {
            get {return this.UTCCreated.ToLocalTime();}
        }

        public virtual DateTime LastUpdated
        {
            get { return this.UTCLastUpdated.ToLocalTime(); }
        }

        public void PerformValidation(System.Data.Linq.ChangeAction action)
        {
            if (action == System.Data.Linq.ChangeAction.Insert || action == System.Data.Linq.ChangeAction.Update)
            {
                if (GetCurrentIdentity() != null)
                {
                    if (action == System.Data.Linq.ChangeAction.Insert)
                    {
                        _UTCLastUpdated = _UTCCreated = DateTime.Now.ToUniversalTime();
                        _LastUpdatedBy = _CreatedBy = GetLoginName();
                    }
                    else if (action == System.Data.Linq.ChangeAction.Update)
                    {
                        _UTCLastUpdated = DateTime.Now.ToUniversalTime();
                        _LastUpdatedBy = GetLoginName();
                    }

                    if (!IsValid)
                    {
                        throw new Errors.ValidationException("Validation Prevented Saving");
                    }
                }
                else
                {
                    throw new ApplicationException("User Not Logged");
                }
            }
        }

        partial void OnValidate(System.Data.Linq.ChangeAction action)
        {
            PerformValidation(action);
        }

        public virtual bool IsValid
        {
            get { return GetRuleViolations().Count() == 0; }
        }

        public virtual IEnumerable<RuleViolation> GetRuleViolations()
        {
            if (string.IsNullOrEmpty(Name))
                yield return new RuleViolation("Name must be set", "Name");
            yield break;
        }

        internal void SetDeleted()
        {
            SetDeleted(true);
        }

        internal void SetDeleted(bool value)
        {
            this._Deleted = value;
        }
    }
}
